package ua.kpi.ipsa.expert.api.db;

import java.util.Arrays;

import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;

public class CodeTuple {

	public int codePK;
	public int codePortionTupleFK;
	public String[] fileName;
	public String text;

	public CodeTuple() {
	}

	public CodeTuple(int codePK) {
		this.codePK = codePK;
	}

	@Override
	public String toString() {
		return "CodeTuple [codePK=" + codePK + ", codePortionTupleFK="
				+ codePortionTupleFK + ", fileName="
				+ Arrays.toString(fileName) + ", text=" + text + "]";
	}

	CodeTuple(DatabaseEntry key, DatabaseEntry data) {
		setKeyEntry(key);
		setValueEntry(data);
	}

	DatabaseEntry getKeyEntry() {
		DatabaseEntry entry = new DatabaseEntry();
		IntegerBinding.intToEntry(codePK, entry);
		return entry;
	}

	void setKeyEntry(DatabaseEntry entry) {
		codePK = IntegerBinding.entryToInt(entry);
	}

	DatabaseEntry getValueEntry() {
		DatabaseEntry entry = new DatabaseEntry();
		TupleOutput out = new TupleOutput();
		out.writeInt(codePortionTupleFK);
		out.writeInt(fileName.length);
		for (String s : fileName)
			out.writeString(s);
		out.writeString(text);
		entry.setData(out.getBufferBytes(), out.getBufferOffset(),
				out.getBufferLength());
		return entry;
	}

	void setValueEntry(DatabaseEntry entry) {
		TupleInput in = new TupleInput(entry.getData(), entry.getOffset(),
				entry.getSize());
		codePortionTupleFK = in.readInt();
		fileName = new String[in.readInt()];
		for (int i = 0; i < fileName.length; ++i)
			fileName[i] = in.readString();
		text = in.readString();
	}

	static final SecondaryKeyCreator CODE_PORTION_CREATOR = new SecondaryKeyCreator() {

		@Override
		public boolean createSecondaryKey(SecondaryDatabase secondary,
				DatabaseEntry key, DatabaseEntry data, DatabaseEntry result) {
			IntegerBinding.intToEntry(
					new CodeTuple(key, data).codePortionTupleFK, result);
			return true;
		}
	};
}
